# encoding:utf-8
from __future__ import unicode_literals

from urlparse import urljoin

from models import MealModel,OrderModel
from django.conf import settings
from django.core.urlresolvers import reverse
from ex import redis_conn,get_random_word

def get_user_single_meal_qr_context(user):
    try:
        meal=MealModel.objects.get(name='single')
    except MealModel.DoesNotExist as e:
        raise UserWarning,'single meal not exist ,you should add this meal'
    single_orders=OrderModel.objects.filter(car__user=user,status='active',meal=meal)
    if single_orders.exists():
        single_order=single_orders[0]
        key=get_random_word()
        expire=getattr(settings,'QR_EXPIRE',60*2) # 默认2分钟过期
        redis_conn.set(key,single_order.pk,ex=expire) 
        dc={
            'status':'success',
            'qr_url':urljoin( settings.URL_ROOT,reverse('qr',args=[key])),
            'key':key,
            'count':len(single_orders),
            'meal_name':'single',
            'meal_label':meal.label,
            'expire':expire,
        }
        return dc  
    else:
        raise UserWarning,'you have not avaliable single order'

#def user_order_qr_context(user):
    #"""
    #obsolet
    #"""
    #ls=[]
    #for meal in MealModel.objects.filter(status='active').order_by('priority'):
        #ls=list(user.ordermodel_set.filter(status='active',meal=meal))
        #if ls:
            #break
    #if ls:
        #order = ls[0]
        #handler = globals()[order.meal.name]()
        #dc= handler.get_qr_context(ls)
        #return dc
    #else:
        #raise UserWarning,'you have not avaliable order'


def consume_chepai(chepai):
    try:
        order = OrderModel.objects.filter(car__car_no=chepai,status='active').order_by('meal__priority').first()
        if not order:
            raise OrderModel.DoesNotExist
        handler=globals()[order.meal.name]()
        handler.consume(order)
        return order
    except OrderModel.DoesNotExist:
        raise UserWarning,'not active order related to Car Number {chepai}'.format(chepai=chepai)
 
def consume_order_key(order_key):
    expire=getattr(settings,'QR_EXPIRE',60*2) # 默认2分钟过期
    try:
        pk = redis_conn.get(order_key)
        redis_conn.set('_for_check_%s'%order_key,pk,ex=expire)
        order = OrderModel.objects.get(pk=pk,status='active')
        handler=globals()[order.meal.name]()
        handler.consume(order)
        return order
    except OrderModel.DoesNotExist:
        raise UserWarning,'active order not exist or key has been expired'

def check_order_key(order_key):
    dc={}
    order_pk = redis_conn.get('_for_check_%s'%order_key)
    if order_pk:
        order = OrderModel.objects.get(pk=order_pk)
        dc['just_now_used']=True
        dc['session']= order.last_session().pk
    elif redis_conn.get(order_key):
        dc['just_now_used']=False
    else:
        dc['msg']='order_key is expired'
    return dc


class single(object):
    #def get_qr_context(self,order_ls):
        #meal=MealModel.objects.get(name='single')
        #key=get_random_word()
        #order=order_ls[0]
        #expire=getattr(settings,'QR_EXPIRE',60*2) # 默认2分钟过期
        #redis_conn.set(key,order.pk,ex=expire) 
        #dc={
            #'status':'success',
            #'qr_url':urljoin( settings.URL_ROOT,reverse('qr',args=[key])),
            #'key':key,
            #'count':len(order_ls),
            #'meal_name':'single',
            #'meal_label':meal.label,
            #'expire':expire,
        #}
        #return dc
    
    def consume(self,order):
        order.status='used'
        order.save()
        return order